/**
 *
 * Dialog control class. Provides modal behavior.
 *
 * @author Andrey Anisimov <hercules@inbox.ru>
 */

import core.ui.Window;
import core.ui.ModalGlassPane;
import core.util.Listeners;

class Dialog extends Window {

	/**
	 * Initializes the dialog.
	 *
	 * @param parent (Window) Parent window
	 * @param x, y (int) Dialog coordinates
	 * @param width, height (int) Dialog size
	 */
	this.Dialog = function(parent, x, y, width, height) {
		super(parent, x, y, width, height);
		this.modal = false;
		this.listeners = new Listeners([
            'onDialogBeginModal',
            'onDialogEndModal',
            'onDialogLooseActivity',
            'onDialogComplete',
            'onDialogCancelled'
        ]);
	}

	/**
	 * Adds the new dialog listener.
	 *
	 * @param listener (object) The listener to add.
	 */
	this.addDialogListener = function(listener) {
		this.listeners.add(listener);
	}

	/**
	 * Removes the dialog listener.
	 *
	 * @param listener (object) The listener to remove.
	 */
	this.removeDialogListener = function(listener) {
		this.listeners.remove(listener);
	}
	
	/**
	 * Displays the dialog in modal state.
	 * 
	 * @param top (Window) [optional] The top window for modal state (all windows by default).
	 */
	this.doModal = function(top) {
		ModalGlassPane.getInstance().modalize(this);
		this.modal = true;
		this.fireBeginModal();
	}
	
	/**
	 * Ends modal state for this dialog.
	 */
	this.endModal = function() {		
		if (!this.isModal()) return;
		ModalGlassPane.getInstance().unmodalize(this);
		this.modal = false;
		this.fireEndModal();
	}
	
	/**
	 * Gets whether this dialog is in modal state.
	 *
	 * @return bool
	 */
	this.isModal = function() {
		return this.modal;
	}

	/**
	 * @protected
	 * Fires when the dialog begins modal state.
	 */
	this.fireBeginModal = function() {
		this.listeners.call('onDialogBeginModal', [ this ]);
	}

	/**
	 * @protected
	 * Fires when the dialog ends its modal state.
	 */
	this.fireEndModal = function() {
		this.listeners.call('onDialogEndModal', [ this ]);
	}

	/**
	 * @protected
	 * Fires when the user clicks on the modal glass page
	 * to activate some window or control under the modal dialog.
	 */
	this.fireLooseActivity = function() {
		this.listeners.call('onDialogLooseActivity', [ this ]);
	}

	/**
	 * @protected
	 * Fires when the user completes the dialog.
	 */
	this.fireComplete = function() {
		this.listeners.call('onDialogComplete', [ this ]);
	}

	/**
	 * @protected
	 * Fires when the user cancelled the dialog.
	 */
	this.fireCancelled = function() {
		this.listeners.call('onDialogCancelled', [ this ]);
	}
}